<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 循环判断大小 -->
    <script>
        var sortedSquares = function () {
            let nums = [-4, -1, 0, 3, 10]
            let newnum = []
            for (let i = 0; i < nums.length; i++) {
                nums[i] *= nums[i]
                if (newnum.length == 0) {
                    newnum.push(nums[i])
                } else if (newnum.length == 1) {
                    if (nums[i] < newnum[0]) {
                        newnum.splice(0, 0, nums[i])
                    } else {
                        newnum.push(nums[i])
                    }
                } else {
                    if (nums[i] < newnum[0]) {
                        newnum.unshift(nums[i])
                    } else if (nums[i] > newnum[newnum.length - 1]) {
                        newnum.push(nums[i])
                    } else {
                        for (let j = 0; j < newnum.length - 1; j++) {
                            if (nums[i] >= newnum[j] && nums[i] <= newnum[j + 1]) {
                                newnum.splice(j + 1, 0, nums[i])
                                break
                            }
                        }
                    }
                }
            }
            return newnum
        };
        console.log(sortedSquares());
    </script>

    <!-- 双指针 题解 -->
    <script>
        const sortedSquares = function (nums) {
            let res = []
            for (let i = 0, j = nums.length - 1; i <= j;) {
                const left = Math.abs(nums[i])
                const right = Math.abs(nums[j])
                if (right > left) {
                    // push element to the front of the array
                    res.unshift(right * right)
                    j--
                } else {
                    res.unshift(left * left)
                    i++
                }
            }
            return res
        }
    </script>
</body>

</html>